package com.bytedance.improvingroad.binder.client

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import com.bytedance.improvingroad.activity.BaseBindingActivity
import com.bytedance.improvingroad.binder.Book
import com.bytedance.improvingroad.binder.server.BookManager
import com.bytedance.improvingroad.binder.server.RemoteService
import com.bytedance.improvingroad.binder.server.Stub
import com.bytedance.improvingroad.databinding.ActivityClientBinding

class ClientActivity : BaseBindingActivity<ActivityClientBinding>() {
    private var bookManager: BookManager? = null

    private val serviceConn = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            Log.e("cx","onServiceConnected--$service")
            bookManager = Stub.asInterface(service)
        }

        override fun onServiceDisconnected(name: ComponentName?) {

        }

    }
    override fun initData() {

        Intent(this,RemoteService::class.java).also {
            it.action = "com.bytedance.improvingroad.binder.server.RemoteService"
            bindService(it,serviceConn,Context.BIND_AUTO_CREATE)
            Toast.makeText(this,"fuck",Toast.LENGTH_SHORT).show()
        }
    }

    override fun initListener() {
        binding.addBtn.setOnClickListener {
            for (i in 1..5) {
                Book().apply {
                    name = "Binder通信--$i"
                    price = i * 10
                }.also { bookManager?.addBook(it) }
            }
            bookManager?.getBooks()?.forEach { book ->
                Log.e("cx",book.toString())
            }
        }
    }
}